package com.linln.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;

@PropertySource({"classpath:/fileMapping.properties"})
@Component
public class PathMappingUtil {


    //头像图片库路径
    public static String IMGPATH;

    //头像图片库映射地址
    public static String IMGPATHMAPPING;

    //核销图片库路径
    public static String VERIFICATIONPATH;

    //核销图片库映射地址
    public static String VERIFICATIONPATHMAPPING;

    //营业执照路径
    public static String BUSINESSLICENSEPATH;

    //实体店门店图路径
    public static String PHYSICALSTOREPATH;

    //施工车间全景路径
    public static String CONSTRUCTIONWORKSHOPPATH;

    //技师施工图路径
    public static String TECHNICIANCONSTRUCTIONPATH;

    //营业执照映射地址
    public static String BUSINESSLICENSEMAPPING;

    //实体店门店图映射地址
    public static String PHYSICALSTOREMAPPING;

    //施工车间全景映射地址
    public static String CONSTRUCTIONWORKSHOPMAPPING;

    //技师施工图映射地址
    public static String TECHNICIANCONSTRUCTIONMAPPING;

    //编辑器图片路径
    public static String EDITORIMGPATH;

    //编辑器图片映射地址
    public static String EDITORIMGMAPPING;

    //轮播图图片路径
    public static String HOMEROTATIONPATH;

    //轮播图图片映射地址
    public static String HOMEROTATIONMAPPING;

    @Value("${homeRotation.path}")
    public void setHOMEROTATIONPATH(String HOMEROTATIONPATH) {
        PathMappingUtil.HOMEROTATIONPATH = HOMEROTATIONPATH;
    }

    @Value("${homeRotation.mapping}")
    public void setHOMEROTATIONMAPPING(String HOMEROTATIONMAPPING) {
        PathMappingUtil.HOMEROTATIONMAPPING = HOMEROTATIONMAPPING;
    }

    @Value("${editorimg.path}")
    public void setEDITORIMGPATH(String EDITORIMGPATH) {
        PathMappingUtil.EDITORIMGPATH = EDITORIMGPATH;
    }

    @Value("${editorimg.mapping}")
    public void setEDITORIMGMAPPING(String EDITORIMGMAPPING) {
        PathMappingUtil.EDITORIMGMAPPING = EDITORIMGMAPPING;
    }

    @Value("${businesslicense.path}")
    public void setBUSINESSLICENSEPATH(String BUSINESSLICENSEPATH) {
        PathMappingUtil.BUSINESSLICENSEPATH = BUSINESSLICENSEPATH;
    }

    @Value("${physicalstore.path}")
    public void setPHYSICALSTOREPATH(String PHYSICALSTOREPATH) {
        PathMappingUtil.PHYSICALSTOREPATH = PHYSICALSTOREPATH;
    }

    @Value("${constructionworkshop.path}")
    public void setCONSTRUCTIONWORKSHOPPATH(String CONSTRUCTIONWORKSHOPPATH) {
        PathMappingUtil.CONSTRUCTIONWORKSHOPPATH = CONSTRUCTIONWORKSHOPPATH;
    }

    @Value("${technicianconstruction.path}")
    public void setTECHNICIANCONSTRUCTIONPATH(String TECHNICIANCONSTRUCTIONPATH) {
        PathMappingUtil.TECHNICIANCONSTRUCTIONPATH = TECHNICIANCONSTRUCTIONPATH;
    }

    @Value("${businesslicense.mapping}")
    public void setBUSINESSLICENSEMAPPING(String BUSINESSLICENSEMAPPING) {
        PathMappingUtil.BUSINESSLICENSEMAPPING = BUSINESSLICENSEMAPPING;
    }

    @Value("${physicalstore.mapping}")
    public void setPHYSICALSTOREMAPPING(String PHYSICALSTOREMAPPING) {
        PathMappingUtil.PHYSICALSTOREMAPPING = PHYSICALSTOREMAPPING;
    }

    @Value("${constructionworkshop.mapping}")
    public void setCONSTRUCTIONWORKSHOPMAPPING(String CONSTRUCTIONWORKSHOPMAPPING) {
        PathMappingUtil.CONSTRUCTIONWORKSHOPMAPPING = CONSTRUCTIONWORKSHOPMAPPING;
    }

    @Value("${technicianconstruction.mapping}")
    public void setTECHNICIANCONSTRUCTIONMAPPING(String TECHNICIANCONSTRUCTIONMAPPING) {
        PathMappingUtil.TECHNICIANCONSTRUCTIONMAPPING = TECHNICIANCONSTRUCTIONMAPPING;
    }

    @Value("${img.path}")
    public void setCarouselpath(String path) {
        IMGPATH = path;
    }

    @Value("${img.mapping}")
    public void setCarouselpathMapping(String pathMapping) {
        IMGPATHMAPPING = pathMapping;
    }

    @Value("${verification.path}")
    public void setVerificationPath(String path) {
        VERIFICATIONPATH = path;
    }

    @Value("${verification.mapping}")
    public void setVerificationPathMapping(String pathMapping) {
        VERIFICATIONPATHMAPPING = pathMapping;
    }

    public static String getPath(String path, String pathMapping) {
        String[] str = pathMapping.split("/");
        String fileName = str[str.length - 1];
        return path + fileName;
    }

    public static String getPathMapping(String path, String pathMapping) {
        String[] str = path.split("/");
        String fileName = str[str.length - 1];
        return pathMapping + fileName;
    }

    public static String formatMapping(String headImg) {
        String[] Mappings = getFilterMapping();
        for (String mapping : Mappings) {
            mapping = mapping.replace("*", "");
            if (headImg.contains(mapping)) {
                String[] headImgs = headImg.split("/");
                headImg = mapping + headImgs[headImgs.length - 1];
                break;
            }
        }
/*        if(headImg.charAt(1)!='/'){
            headImg="/"+headImg;
        }*/
        return headImg;
    }

    public static String formatUrl(String ip, String img) {
        if (ip.substring(ip.length() - 1).equals("/") && img.substring(0, 1).equals("/")) {
            return ip + img.substring(1);
        } else if (!ip.substring(ip.length() - 1).equals("/") && !img.substring(0).equals("/")) {
            return ip + "/" + img;
        } else {
            return ip + img;
        }
    }

    public static String[] getFilterMapping() {
        //图片映射文件过滤封装
        Properties prop = new Properties();
        List<String> filterMaping = new ArrayList<>();
        InputStream in = PathMappingUtil.class.getClassLoader().getResourceAsStream("fileMapping.properties");
        try {
            prop.load(in);
            Set<Object> keyset = prop.keySet();
            for (Object object : keyset) {
                String key = object.toString();
                if (key.contains("mapping")) {
                    filterMaping.add(prop.getProperty(key) + "**");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return filterMaping.toArray(new String[0]);
    }

    public static String saveImg(String path, String pathMapping, MultipartFile img) {
        //获取附件名字
        String filename = img.getOriginalFilename();
        File filepath = new File(path, filename);
        //判断路径是否存在，没有就创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }

        //设置附件存在磁盘中的名字 为 8为的uuid+源文件的后缀名
        filename = UUIDUtil.randomUUID8() + filename.substring(filename.lastIndexOf('.'));
        //将上传图片保存到一个磁盘中
        File file = new File(path + File.separator + filename);
        //保存到磁盘中
        try {
            img.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pathMapping + filename;
    }

    /**
     * base64转MultipartFile
     *
     * @param base64
     * @return
     */
    public static MultipartFile base64ToMultipart(String base64) {
        String[] baseStrs = base64.split(",");
        byte[] b;
        b = Base64.decodeBase64(baseStrs[1]);
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }
        return new Base64DecodedMultipartFile(b, baseStrs[0]);
    }

}

class Base64DecodedMultipartFile implements MultipartFile {

    private final byte[] imgContent;
    private final String header;

    public Base64DecodedMultipartFile(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    @Override
    public String getName() {
        // TODO - implementation depends on your requirements
        return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        // TODO - implementation depends on your requirements
        return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
    }

    @Override
    public String getContentType() {
        // TODO - implementation depends on your requirements
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(imgContent);
    }

}
